import React, { useState, useEffect, useRef, useCallback } from "react";
import WakeIndicator from "./WakeIndicator";

interface WakeManagerProps {
    onWakeDetected: () => void;
}

const WakeManager: React.FC<WakeManagerProps> = ({ onWakeDetected }) => {
    const [isWakeListening, setIsWakeListening] = useState(false);
    const [isInitialized, setIsInitialized] = useState(false);
    const [errorCount, setErrorCount] = useState(0);
    const wakeRecognitionRef = useRef<any>(null);
    const restartTimeoutRef = useRef<NodeJS.Timeout | null>(null);

    // 开始语音唤醒监听
    const startWakeListening = useCallback(() => {
        if (wakeRecognitionRef.current && !isWakeListening && isInitialized) {
            try {
                wakeRecognitionRef.current.start();
            } catch (error) {
                console.error("启动语音唤醒失败:", error);
                // 如果启动失败，延迟重试
                if (restartTimeoutRef.current) {
                    clearTimeout(restartTimeoutRef.current);
                }
                restartTimeoutRef.current = setTimeout(() => {
                    startWakeListening();
                }, 2000);
            }
        }
    }, [isWakeListening, isInitialized]);

    // 停止语音唤醒监听
    const stopWakeListening = useCallback(() => {
        if (wakeRecognitionRef.current) {
            try {
                wakeRecognitionRef.current.stop();
                setIsWakeListening(false);
            } catch (error) {
                console.error("停止语音唤醒失败:", error);
            }
        }
    }, []);

    useEffect(() => {
        if (
            typeof window !== "undefined" &&
            "webkitSpeechRecognition" in window
        ) {
            // 清理之前的实例
            if (wakeRecognitionRef.current) {
                try {
                    wakeRecognitionRef.current.stop();
                } catch (error) {
                    // 忽略停止时的错误
                }
            }

            // 语音唤醒识别
            wakeRecognitionRef.current = new (
                window as any
            ).webkitSpeechRecognition();
            wakeRecognitionRef.current.continuous = true;
            wakeRecognitionRef.current.interimResults = true;
            wakeRecognitionRef.current.lang = "zh-CN";

            wakeRecognitionRef.current.onstart = () => {
                setIsWakeListening(true);
                setErrorCount(0); // 重置错误计数
                console.log("语音唤醒监听已开启");
            };

            wakeRecognitionRef.current.onresult = (event: any) => {
                let finalTranscript = "";
                for (let i = event.resultIndex; i < event.results.length; i++) {
                    if (event.results[i].isFinal) {
                        finalTranscript += event.results[i][0].transcript;
                    }
                }

                // 检查唤醒词
                if (
                    finalTranscript.toLowerCase().includes("小维") ||
                    finalTranscript.toLowerCase().includes("小伟") ||
                    finalTranscript.toLowerCase().includes("小薇")
                ) {
                    console.log("检测到唤醒词:", finalTranscript);
                    // 停止唤醒监听
                    stopWakeListening();
                    // 触发唤醒事件
                    onWakeDetected();
                    // 延迟后重新开始监听
                    setTimeout(() => {
                        startWakeListening();
                    }, 2000);
                }
            };

            wakeRecognitionRef.current.onend = () => {
                // 如果不是因为检测到唤醒词而停止，则重新开始监听
                if (isWakeListening) {
                    setIsWakeListening(false);
                    // 延迟重启，避免立即重启导致的冲突
                    if (restartTimeoutRef.current) {
                        clearTimeout(restartTimeoutRef.current);
                    }
                    restartTimeoutRef.current = setTimeout(() => {
                        startWakeListening();
                    }, 500);
                }
            };

            wakeRecognitionRef.current.onerror = (event: any) => {
                console.error("唤醒语音识别错误:", event.error);
                setIsWakeListening(false);

                // 增加错误计数
                setErrorCount((prev) => prev + 1);

                // 根据错误类型和错误次数决定重试策略
                let retryDelay = 1000;

                if (event.error === "aborted") {
                    // aborted 错误通常是因为快速重启导致的，增加延迟
                    retryDelay = 2000;
                } else if (event.error === "no-speech") {
                    // 无语音输入，使用较短延迟
                    retryDelay = 500;
                } else if (event.error === "network") {
                    // 网络错误，使用较长延迟
                    retryDelay = 3000;
                }

                // 如果错误次数过多，增加延迟
                if (errorCount > 5) {
                    retryDelay = Math.min(retryDelay * 2, 10000);
                }

                if (restartTimeoutRef.current) {
                    clearTimeout(restartTimeoutRef.current);
                }
                restartTimeoutRef.current = setTimeout(() => {
                    startWakeListening();
                }, retryDelay);
            };

            setIsInitialized(true);
            // 开始语音唤醒监听
            startWakeListening();
        } else {
            console.warn("浏览器不支持语音识别功能");
        }

        return () => {
            // 清理定时器
            if (restartTimeoutRef.current) {
                clearTimeout(restartTimeoutRef.current);
            }
            stopWakeListening();
        };
    }, []); // 移除依赖数组中的 isWakeListening 和 onWakeDetected

    return (
        <WakeIndicator
            isWakeListening={isWakeListening}
            onWakeDetected={onWakeDetected}
        />
    );
};

export default WakeManager;
